﻿using OpenTK.Graphics.OpenGL;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;

namespace ImageTour
{
    class BackgroundModel : IDisposable
    {
        public List<Quad> Quads;
        public List<int> Textures = new List<int>();
        bool disposed = false;
        public BackgroundModel(Mesh m)
        {
            Quads = m.Quads;
            foreach (var tex in m.Textures)
            {
                Textures.Add(GenTexture(tex));
            }
        }

        private int GenTexture(Bitmap bitmap)
        {
            GL.Enable(EnableCap.Texture2D);
            int texId;
            GL.GenTextures(1, out texId);
            GL.BindTexture(TextureTarget.Texture2D, texId);
            BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
                OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);

            bitmap.UnlockBits(data);
            GL.TexParameter(TextureTarget.Texture2D, (TextureParameterName)ExtTextureFilterAnisotropic.TextureMaxAnisotropyExt, 16);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);
            return texId;
        }

        public void Draw()
        {
            GL.Color4(1.0, 1.0, 1.0, 1.0);
            for (int i = 0; i<Quads.Count; i++)
            {
                GL.BindTexture(TextureTarget.Texture2D, Textures[i]);
                DrawQuad(Quads[i]);
            }
        }

        private void DrawQuad(Quad quad)
        {
            GL.Begin(BeginMode.Quads);
            {
                GL.TexCoord2(Mesh.texCoords[0].x, Mesh.texCoords[0].y);
                GL.Vertex3(quad.V1.x, quad.V1.y, quad.V1.z);

                GL.TexCoord2(Mesh.texCoords[1].x, Mesh.texCoords[1].y);
                GL.Vertex3(quad.V2.x, quad.V2.y, quad.V2.z);

                GL.TexCoord2(Mesh.texCoords[2].x, Mesh.texCoords[2].y);
                GL.Vertex3(quad.V3.x, quad.V3.y, quad.V3.z);

                GL.TexCoord2(Mesh.texCoords[3].x, Mesh.texCoords[3].y);
                GL.Vertex3(quad.V4.x, quad.V4.y, quad.V4.z);
            }
            GL.End();
        }

        public void Dispose()
        {
            if (!disposed)
            {
                foreach (var tex in Textures)
                    GL.DeleteTexture(tex);
            }
            disposed = true;
        }
    }
}
